package com.example.backstage.service.Impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.example.front.config.PasswordTokenCache;
import com.example.backstage.dao.UserDao;
import com.example.backstage.service.UserService;
import com.example.gok_mall.constUtil.ConstUtil;
import com.example.gok_mall.entity.User;
import com.example.gok_mall.reponseData.ResultData;
import com.example.gok_mall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    public UserDao userDao;

    @Override
    public ResultData queryUserByUsernameAndPassword(String userName, String password) {
        //对用户提交的密码进行一次加密操作
        String encryptionPassword = DigestUtil.md5Hex(password);

        User user = userDao.queryUserByUsernameAndPassword(userName, encryptionPassword);
        if (user == null) {
            return ResultData.fail("用户或密码错误");
        }
        return ResultData.createData(user);
    }

    @Override
    public ResultData queryUserPasswordQuestion(String userName) {
        String question = userDao.queryUserPasswordQuestion(userName);
        if (question != null) {
            return ResultData.createData(question);
        }
        return ResultData.fail("该用户未设置找回密码问题");
    }

    @Override
    public ResultData checkUserPasswordAnswer(String username, String question, String answer) {
        int i = userDao.checkUserPasswordAnswer(username, question, answer);
        if (i <= 0) {
            return ResultData.fail("问题输入不正确，验证失败请重试");
        }
        //如果验证成功，先生成一个token凭证
        String token = UUID.randomUUID().toString();
        //String token = JwtUtil.createToken(username);
        //需要将token放入本地服务器缓存
        PasswordTokenCache.putToken(username, token);

        //将token凭证发送给前端
        //return ResultData.createData(token);
        return ResultData.createData(token);
    }

    @Override
    //忘记密码状态下重置密码
    public ResultData resetPasswordByToken(String username, String password, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)) {
            return ResultData.fail("参数错误，token需要传递");
        }
        ResultData validResponse = this.checkValid(username, ConstUtil.USERNAME);

        if (validResponse.isSuccess()) {
            //用户不存在
            return ResultData.fail("用户不存在");
        }
        //将原来使用GuavaCache存储的Token迁移到Redis里面
        //String token = RedisShardePoolUtil.get(ConstUtil.TOKEN_PREFIX+username);
        String token = PasswordTokenCache.getTokenByUsername(username);
        if (StringUtils.isBlank(forgetToken)) {
            return ResultData.fail("token无效或者过期");
        }

        if (StringUtils.equals(forgetToken, token)) {

            String md5Password = MD5Util.MD5EncodeUtf8(password);

            int rowCount = userDao.updatePasswordByUsername(username, md5Password);

            if (rowCount > 0) {
                return ResultData.success("修改密码成功");
            }
        } else {
            return ResultData.fail("token错误，请重新获取重置密码的token");
        }
        return ResultData.fail("修改密码失败");
    }

    @Override
    public ResultData updateUser(User user) {
        //username是不能被更新的
        //email也要进行校验，校验新的email是不是已经存在，如果当存在相同的email的话，不能是我们当前的用户的

        int resuletCount=userDao.checkEmailByUserId(user.getEmail(),user.getId());

        if(resuletCount>0){
            return ResultData.fail("邮箱已被使用,请更换后重试");
        }

        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount=userDao.updateByPrimaryKeySelective(updateUser);

        if(updateCount>0){
            return  ResultData.success("更行个人信息成功");
        }
        return ResultData.fail("更新个人信息失败,请稍后重试");
//
//        //对用户提交的密码进行一次加密操作
//        String encryptionPassword = DigestUtil.md5Hex(user.getPassword());
//        user.setPassword(encryptionPassword);
//        int user1 = userDao.updateUser(user);
//        return ResultData.success("信息更新成功");
    }

    @Override
    public ResultData addUser(User user) {
        ResultData validResponse = this.checkValid(user.getUsername(), ConstUtil.USERNAME);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }

        validResponse = this.checkValid(user.getEmail(), ConstUtil.EMAIL);
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        user.setRole(ConstUtil.Role.ROLE_CUSTOMER);
        //对用户提交的密码进行一次加密操作
        String encryptionPassword = DigestUtil.md5Hex(user.getPassword());
        user.setPassword(encryptionPassword);
        int user2 = userDao.insert(user);
        if (user2 == 0) {
            return ResultData.fail("服务器故障，无法注册");
        }
        return ResultData.success("用户注册成功");
    }

    @Override
    //判断用户名和邮箱是否有效
    public ResultData checkValid(String str, String type) {
        if (StringUtils.isNotBlank(type)) {
            //开始校验
            if (ConstUtil.USERNAME.equals(type)) {
                int resultCount = userDao.checkUsername(str);
                if (resultCount > 0) {
                    return ResultData.fail("用户名已存在");
                }
            }
            if (ConstUtil.EMAIL.equals(type)) {
                int resultCount = userDao.checkEmail(str);

                if (resultCount > 0) {
                    return ResultData.fail("email已存在");
                }
            }
        } else {
            return ResultData.fail("参数错误");
        }
        return ResultData.success("校验成功");
    }

    @Override
    public ResultData resetPassword(String passwordOld, String passwordNew, User user) {
        //防止横向越权，要校验一下这个用户的旧密码，一定要指向这个用户。因为我们会查询一个count(1),如果不指定id,那么结果可能就是true  count>0
        int resultCount = userDao.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if (resultCount == 0) {
            return ResultData.fail("旧密码错误，修改失败");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));

        int updateCount = userDao.updateByPrimaryKeySelective(user);

        if (updateCount > 0) {
            return ResultData.success("修改成功");
        }
        return ResultData.fail("密码更新失败");
    }

    @Override
    public ResultData checkAdminRole(User user) {
            if(user!=null&&user.getRole().intValue()==ConstUtil.Role.ROLE_ADMIN){
                return ResultData.success("管理员登录");
            }
            return ResultData.fail("当前用户并不是管理员");
        }

}



